package com.slh.touchandroid.fragment;

import java.util.List;

import android.content.pm.ApplicationInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.slh.touchandroid.R;
import com.slh.touchandroid.adapter.AppAdapter;
import com.slh.touchandroid.utils.AppUtils;

public class RunningAppsFragment extends Fragment {
	private List<ApplicationInfo> mApplicationInfos;
	private AppAdapter mAppAdapter;
	private ListView mAppListView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setRetainInstance(true);
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_list, container,
				false);
		mAppListView = (ListView) rootView
				.findViewWithTag(getString(R.string.tag_list));
		loadApps();
		return rootView;
	}

	// ===================================================================
	private void loadApps() {
		new AsyncTask<Void, Void, List<ApplicationInfo>>() {

			@Override
			protected List<ApplicationInfo> doInBackground(Void... params) {
				return AppUtils.getInstalledApplication(getActivity(),
						AppUtils.FILTER_APPS_RUNNING);
			}

			@Override
			protected void onPostExecute(List<ApplicationInfo> result) {
				mApplicationInfos = result;
				mAppAdapter = new AppAdapter(getActivity(), mApplicationInfos,
						R.layout.row_common_vertical);
				mAppListView.setAdapter(mAppAdapter);
				super.onPostExecute(result);
			}
		}.execute();
	}

}
